package com.huijie.app.u.controller;


import com.huijie.app.u.bean.UserEditVO;
import com.huijie.app.u.entity.User;
import com.huijie.app.u.service.IRoleService;
import com.huijie.app.u.service.IUserService;
import com.huijie.app.sys.aspect.ControllerParamRecord;
import com.huijie.app.sys.aspect.ControllerParamValid;
import com.huijie.core.bean.ResponseBean;
import com.huijie.core.bean.ResponseCodeMsgBean;
import com.huijie.core.constant.BussinessCode;
import com.huijie.core.constant.ResponseCode;
import com.huijie.core.util.ResponseMsgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.huijie.core.common.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

import static com.huijie.app.util.TokenUtil.getUserLoginName;
import static com.huijie.core.constant.Constants.*;
import static com.huijie.core.constant.Constants.STATUS_OF_0;
import static com.huijie.core.constant.Constants.TIPS_DEL;
import static com.huijie.core.util.ResponseMsgUtil.ERROR_CODE_SYSTEM;
import static com.huijie.core.util.ResponseMsgUtil.VALIDATOR_CODE_SYSTEM;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author echen
 * @since 2019-01-09
 */
@RestController
@Api(tags = {"5-1、用户中心API-用户"}, position = 9)
@RequestMapping("/u/user")
public class UserController extends BaseController {

    private final IUserService userService;
    private final IRoleService roleService;

    @Autowired
    public UserController(IUserService userService, IRoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    /**
     * @param userEditVO    用户编辑表单 前端抽象实体
     * @param bindingResult 校验结果
     * @param request       请求
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 新增用户信息
     * @author Alex
     * @date 2018/9/25 13:12
     */
    @ControllerParamValid
    @ApiOperation(value = "新增用户信息", notes = "新增用户信息")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @PostMapping(value = "", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
    @ControllerParamRecord(description = "新增用户信息")
    public ResponseEntity<ResponseBean> insertUser(@Valid @RequestBody UserEditVO userEditVO, BindingResult bindingResult, HttpServletRequest request) {
        ResponseBean rb;
        if (StringUtils.isEmpty(userEditVO.getUserLoginName()) || StringUtils.isEmpty(userEditVO.getUserName()) || StringUtils.isEmpty(userEditVO.getUserPassword())) {
            rb = new ResponseBean(BussinessCode.PARAM_NONE.getCode(), BussinessCode.PARAM_NONE.getMessage());
            return ResponseEntity.ok(rb);
        }
        String userLoginName = getUserLoginName(request);
        // 验证用户账号唯一性
        if (userService.selectUserLoginNameCheck(userEditVO.getUserLoginName(), null)) {
            return ResponseEntity.ok(ResponseMsgUtil.returnCodeMessage(BussinessCode.USER_LOGIN_NAME_EXIST, null));
        }
        if (null == userEditVO.getUserStatus()) {
            userEditVO.setUserStatus(STATUS_0);
        }
        User user = new User();
        BeanUtils.copyProperties(userEditVO, user);
        user = userService.insertUser(user, userLoginName);
        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, user);
        return ResponseEntity.ok(rb);
    }

//    /**
//     * @param userEditVO 用户编辑表单 前端抽象实体
//     * @return com.cn.rfid.model.vo.base.BussinessMsg
//     * @description: 更新用户主体信息
//     * @author Alex
//     * @date 2018/9/20 16:38
//     */
//    @ControllerParamValid
//    @ApiOperation(value = "更新用户主体信息", notes = "更新用户主体信息")
//    @ApiResponses(value = {
//            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
//            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
//    @PatchMapping(value = "/{id}/master", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
//    @ControllerParamRecord(description = "更新用户主体信息")
//    public ResponseEntity<ResponseBean> updateUser(@Valid @RequestBody UserEditVO userEditVO, BindingResult bindingResult, HttpServletRequest request, @PathVariable Integer id) {
//        ResponseBean rb;
//        if (id < STATUS_OF_0) {
//            rb = new ResponseBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
//            return ResponseEntity.ok(rb);
//        }
//        // 验证用户账号唯一性
//        Long checkUserLoginName = userMapper.selectUserLoginNameCheck(userEditVO.getUserLoginName(), id);
//        if (checkUserLoginName.intValue() > 0) {
//            return ResponseEntity.ok(ResponseMsgUtil.returnCodeMessage(BussinessCode.USER_LOGIN_NAME_EXIST, null));
//        }
//        String userLoginName = getUserLoginName(request);
//        if (null == userEditVO.getUserStatus()) {
//            userEditVO.setUserStatus(STATUS_0);
//        }
//        UserEditDTO userEditDTO = new UserEditDTO();
//        BeanUtils.copyProperties(userEditVO, userEditDTO);
//        userEditDTO.setUserId(id);
//        User user = userService.updateUser(userEditDTO, userLoginName);
//        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, user);
//        return ResponseEntity.ok(rb);
//    }

    /**
     * @param id      用户ID
     * @param request 请求
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 失效用户
     * @author Alex
     * @date 2018/9/25 14:31
     */
    @ApiOperation(value = "失效用户", notes = "失效用户")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @PatchMapping(value = "/{id}/status", produces = API_RESPONSE_PRODUCES)
    @ControllerParamRecord(description = "失效用户信息")
    public ResponseEntity<ResponseBean> updateUserStatusFail(HttpServletRequest request, @PathVariable Integer id) {
        ResponseBean rb;
        if (id < STATUS_OF_0) {
            rb = new ResponseBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
            return ResponseEntity.ok(rb);
        }
        User user = userService.updateUserStatus(id);
        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, user);
        return ResponseEntity.ok(rb);
    }

    /**
     * @param ids 用户ID数组
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 批量失效用户
     * @author Alex
     * @date 2018/9/25 14:35
     */
    @ApiOperation(value = "批量失效用户", notes = "批量失效用户")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @PatchMapping(value = "/status", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
    @ControllerParamRecord(description = "批量失效用户信息")
    public ResponseEntity<ResponseBean> batchUpdateUserStatusFail(@RequestBody Integer[] ids, HttpServletRequest request) {
        ResponseBean rb;
        //验证ids不能为空
        if (ids.length <= 0) {
            rb = new ResponseBean(BussinessCode.IDARRAY_LENGTH_LESS_THAN_0.getCode(), BussinessCode.IDARRAY_LENGTH_LESS_THAN_0.getMessage());
            return ResponseEntity.ok(rb);
        } else {
            for (Integer id : ids) {
                if (id < STATUS_OF_0) {
                    rb = new ResponseBean(BussinessCode.IDARRAY_ELEMENT_LESS_THAN_0.getCode(), BussinessCode.IDARRAY_ELEMENT_LESS_THAN_0.getMessage());
                    return ResponseEntity.ok(rb);
                }
            }
        }
        userService.updateUserBatchStatus(ids, getUserLoginName(request));
        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, ids);
        return ResponseEntity.ok(rb);
    }

    @ApiOperation(value = "删除用户", notes = "删除用户")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @DeleteMapping(value = "/{id}", produces = API_RESPONSE_PRODUCES)
    public ResponseEntity<ResponseCodeMsgBean> deleteUser(@PathVariable Integer id) {
        ResponseCodeMsgBean rcmb;
        if (id < STATUS_OF_0) {
            rcmb = new ResponseCodeMsgBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
            return ResponseEntity.ok(rcmb);
        }
        if (userService.getById(id) == null) {
            rcmb = new ResponseCodeMsgBean(BussinessCode.USER_NONE.getCode(), BussinessCode.USER_NONE.getMessage());
            return ResponseEntity.ok(rcmb);
        }
        userService.deleteUser(id);
        rcmb = ResponseMsgUtil.returnCodeMessageBean(BussinessCode.GLOBAL_SUCCESS);
        return ResponseEntity.ok(rcmb);
    }

//    /**
//     * @param ids 用户ID数组
//     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
//     * @description: 查询待分配的角色信息(用以给用户分配角色时显示)
//     * @author Alex
//     * @date 2018/9/25 15:36
//     */
//    @ApiOperation(value = "查询待分配的角色信息", notes = "查询待分配的角色信息(用以给用户分配角色时显示)")
//    @ApiResponses(value = {
//            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
//            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
//    @GetMapping(value = "/{ids}/undistributed-role", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
//    public ResponseEntity<ResponseBean> listUndistributedRole(@PathVariable String ids) {
//        ResponseBean rb;
//        List<Role> roleList = roleService.selectUserRoleByRoleIdList(ids);
//        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, roleList);
//        return ResponseEntity.ok(rb);
//    }

//    /**
//     * @param ids 用户ID数组
//     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
//     * @description: 查询已分配的角色信息(用以给用户分配角色时显示)
//     * @author Alex
//     * @date 2018/9/25 15:42
//     */
//    @ApiOperation(value = "查询已分配的角色信息", notes = "查询已分配的角色信息(用以给用户分配角色时显示)")
//    @ApiResponses(value = {
//            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
//            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
//    @GetMapping(value = "/{ids}/deceased-role")
//    public ResponseEntity<ResponseBean> listDeceasedUser(@PathVariable String ids) {
//        ResponseBean rb;
//        List<Role> roleList = roleService.selectDeceasedUserRoleByRoleIdList(ids);
//        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, roleList);
//        return ResponseEntity.ok(rb);
//    }

//    /**
//     * @param id 用户ID数组
//     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
//     * @description: 根据用户ID查询已分配的角色信息(用以给用户分配角色时显示)
//     * @author Alex
//     * @date 2018/9/25 15:42
//     */
//    @ApiOperation(value = "查询已分配的角色信息", notes = "根据用户ID查询已分配的角色信息(用以给用户分配角色时显示)")
//    @ApiResponses(value = {
//            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
//            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
//    @GetMapping(value = "/{id}/deceased-role")
//    public ResponseEntity<ResponseBean> listDeceasedUser(@PathVariable Integer id) {
//        ResponseBean rb;
//        if (id < STATUS_OF_0) {
//            rb = new ResponseBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
//            return ResponseEntity.ok(rb);
//        }
//        String roleIdsStr = roleService.getDeceasedUserRoleByUserId(id);
//        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, roleIdsStr);
//        return ResponseEntity.ok(rb);
//    }

    /**
     * @param roleIds 分配的角色ID复数
     * @param request 请求
     * @param id      用户Id
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 新增用户分配角色
     * @author Alex
     * @date 2018/9/25 16:06
     */
    @ApiOperation(value = "新增用户分配角色", notes = "新增用户分配角色")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @PostMapping(value = "/{id}/user-role", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
    @ControllerParamRecord(description = "新增用户分配角色")
    public ResponseEntity<ResponseBean> insertUserRole(@RequestBody() String roleIds, HttpServletRequest request, @PathVariable Integer id) {
        ResponseBean rb;
        if (id < STATUS_OF_0) {
            rb = new ResponseBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
            return ResponseEntity.ok(rb);
        }
        String[] roleIdsAttr = roleIds.split(SAPERATOR_COMMA);
        boolean flag = (roleIdsAttr.length == 1) && (Integer.parseInt(roleIds) < ID_MINIMUN);
        if (flag) {
            rb = new ResponseBean(BussinessCode.IDARRAY_ELEMENT_LESS_THAN_MINIMUN.getCode(),
                    BussinessCode.IDARRAY_ELEMENT_LESS_THAN_MINIMUN.getMessage());
            return ResponseEntity.ok(rb);
        } else if (roleIdsAttr.length > 1) {
            for (int i = 0; i < roleIdsAttr.length; i++) {
                if (Integer.parseInt(roleIdsAttr[i]) < STATUS_OF_0) {
                    rb = new ResponseBean(BussinessCode.IDARRAY_ELEMENT_LESS_THAN_0.getCode(),
                            BussinessCode.IDARRAY_ELEMENT_LESS_THAN_0.getMessage());
                    return ResponseEntity.ok(rb);
                }
            }
        }
        userService.saveUserRole(id, roleIds, getUserLoginName(request));
        Map<String, Object> map = new HashMap<>(4);
        map.put("resId", id);
        map.put("roleIds", roleIds);
        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, map);
        return ResponseEntity.ok(rb);
    }

//    /**
//     * @param userd   用户详细实体
//     * @param request 请求
//     * @param id      用户ID
//     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
//     * @description: 更新用户详细信息
//     * @author Alex
//     * @date 2018/9/25 16:19
//     */
//    @ControllerParamValid
//    @ApiOperation(value = "更新用户详细信息", notes = "更新用户详细信息")
//    @ApiResponses(value = {
//            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
//            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
//    @PostMapping(value = "/{id}/user-detail", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
//    @ControllerParamRecord(description = "更新用户详细信息")
//    public ResponseEntity<ResponseBean> updateUserDetail(@Valid @RequestBody UserDetail userd,
//                                                         final HttpServletRequest request, @PathVariable Integer id) {
//        ResponseBean rb;
//        // 验证po参数
//        if (userd == null) {
//            rb = new ResponseBean(BussinessCode.PARAM_NONE.getCode(), BussinessCode.PARAM_NONE.getMessage());
//            return ResponseEntity.ok(rb);
//        }
//        if (id < STATUS_OF_0) {
//            rb = new ResponseBean(BussinessCode.ID_LESS_THAN_0.getCode(), BussinessCode.ID_LESS_THAN_0.getMessage());
//            return ResponseEntity.ok(rb);
//        }
//        userd.setUserId(id);
//        try {
//            userd = userDetailService.modifyOrUpdateUser(userd, getUserLoginName(request));
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, userd);
//        return ResponseEntity.ok(rb);
//    }

    /**
     * @param userLoginName 用户登录账号
     * @param userPassword  用户登录密码
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 验证用户密码
     * @author Alex
     * @date 2018/9/25 16:25
     */
    @ApiOperation(value = "验证用户密码", notes = "验证用户密码")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @GetMapping(value = "/password-validation")
    public ResponseEntity<ResponseCodeMsgBean> validateUserpd(@RequestParam() String userLoginName, @RequestParam() String userPassword) {
        ResponseCodeMsgBean rb;
        boolean validationResult = userService.validate(userLoginName, userPassword);
        if (validationResult) {
            rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS);
        } else {
            rb = ResponseMsgUtil.returnCodeMessageBean(BussinessCode.USER_PASSWORD_INCORRECT);
        }
        return ResponseEntity.ok(rb);
    }

    /**
     * @param password      密码
     * @param userLoginName 账号
     * @return org.springframework.http.ResponseEntity<com.cn.rfid.model.vo.base.ResponseBean>
     * @description: 通过用户名修改用户密码
     * @author Alex
     * @date 2018/9/25 17:08
     */
    @ApiOperation(value = "修改用户密码", notes = "通过用户名修改用户密码")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @PatchMapping(value = "/{userLoginName}/password", produces = API_RESPONSE_PRODUCES, consumes = API_REQUEST_CONSUMES)
    public ResponseEntity<ResponseCodeMsgBean> updateUserPassword(@Valid @RequestBody String password, @PathVariable String userLoginName) {
        ResponseCodeMsgBean rb;
        //验证用户账号密码
//        if (userService.validate(userLoginName, password)) {
//            return ResponseEntity.ok(ResponseMsgUtil.returnCodeMessageBean(BussinessCode.USER_PASSWORD_INCORRECT));
//        }
        userService.modifyUserPasswordByUserLoginName(userLoginName,password);
        rb = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS);
        return ResponseEntity.ok(rb);
    }

    @ApiOperation(value = "批量删除用户", notes = "批量删除用户")
    @ApiResponses(value = {
            @ApiResponse(code = VALIDATOR_CODE_SYSTEM, message = API_RESPONSE_VALID_ERROR_MESSAGE),
            @ApiResponse(code = ERROR_CODE_SYSTEM, message = API_RESPONSE_SYSTEM_EXCEPTION_MESSAGE)})
    @DeleteMapping("/inv-note/cancellation")
    public ResponseEntity<ResponseBean> batchDeleteUser(@RequestBody Integer[] ids, HttpServletRequest request) {
        ResponseBean rBean;
        if (ids.length <= STATUS_OF_0) {
            rBean = new ResponseBean(BussinessCode.IDARRAY_LENGTH_LESS_THAN_0.getCode(), BussinessCode.IDARRAY_LENGTH_LESS_THAN_0.getMessage());
            return ResponseEntity.ok(rBean);
        }
        Integer delCount = userService.batchDeleteUser(ids);
        rBean = ResponseMsgUtil.returnCodeMessage(ResponseCode.GLOBAL_SUCCESS, null);
        rBean.setData(TIPS_DEL + delCount);
        return ResponseEntity.ok(rBean);
    }
}
